<template>
  <MyDrawer ref="MyRef" title="账号设置" @submit="submit" :disabled="drawerProps.disabled" width="30%">
    <el-form :model="drawerProps.rowData" label-width="120" :rules="rules" ref="formRef" :disabled="drawerProps.disabled">
      <el-form-item label="账号名称" prop="username">
        <el-input v-model="drawerProps.rowData.username"></el-input>
      </el-form-item>
      <el-form-item label="排序值">
        <el-input-number v-model="drawerProps.rowData.sort" :min="1" :max="999999"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="drawerProps.rowData.status" active-text="启用" inactive-text="停用"></el-switch>
      </el-form-item>
      <el-form-item label="角色选择" prop="roleId">
        <el-select v-model="drawerProps.rowData.roleId" :disabled="drawerProps.isEdit">
          <el-option v-for="p in drawerProps.roleList" :key="p.id" :value="p.id" :label="p.roleName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input type="text" v-model="drawerProps.rowData.phone" :disabled="drawerProps.isEdit"></el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <ValidPhone
          v-model:code="drawerProps.rowData.code"
          :phone="drawerProps.rowData.phone"
          session-name="account_name"
          :disabled="drawerProps.isEdit"
        ></ValidPhone>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input type="text" :disabled="drawerProps.isEdit" v-model="drawerProps.rowData.realName"></el-input>
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCard">
        <el-input type="text" :disabled="drawerProps.isEdit" v-model="drawerProps.rowData.idCard"></el-input>
      </el-form-item>
      <el-form-item label="二维码">
        <div>
          <div class="w-[150px] h-[150px]" style="border: 2px dashed var(--el-color-info-light-3)">
            <el-image :src="drawerProps.rowData.qrcode"></el-image>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </MyDrawer>
</template>

<script setup lang="ts">
import { Account } from "@/api/interface/account";
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ref, watch } from "vue";
import { Role } from "@/api/interface/role";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { validUsername, checkPhoneNumber, checkIdCard } from "@/utils/eleValidate";
import ValidPhone from "@/components/validPhone/index.vue";
import { genCode } from "@/api/modules/account";

const MyRef = ref<InstanceType<typeof MyDrawer> | null>();

interface DrawerProps {
  rowData: Account.Option;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
  roleList: Role.Option[];
  isEdit?: boolean;
  pid: any;
  disabled: boolean;
}

// ------------初始化数据
const initData: Account.Option = {
  username: "",
  phone: "",
  idCard: "",
  avatar: "",
  roleId: undefined,
  status: true,
  sort: 1,
  realName: "",
  code: "",
  qrcode: ""
};

// ---------------规则
// 校验角色
const validRole = (rule: any, value: any, callback: any) => {
  if (value === 0 || typeof value !== "number") return callback(new Error("必须选择角色"));
  callback();
};

const rules: FormRules = {
  username: [
    { required: true, message: "名称必须" },
    { validator: validUsername },
    { min: 5, max: 20, message: "账号名称长度在5-20之间" }
  ],
  avatar: [{ required: true, message: "头像不可为空" }],
  roleId: [{ required: true, message: "必须选择角色" }, { validator: validRole }],
  phone: [{ required: true, validator: checkPhoneNumber }],
  idCard: [{ required: true, validator: checkIdCard }],
  realName: [{ required: true, max: 10, min: 2, message: "姓名字数在2-10个字之间" }]
};

const drawerProps = ref<DrawerProps>({
  rowData: JSON.parse(JSON.stringify(initData)),
  roleList: [],
  isEdit: false,
  pid: "",
  disabled: false
});
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  if (!params.rowData) {
    drawerProps.value.rowData = JSON.parse(JSON.stringify(initData));
  } else {
    drawerProps.value.isEdit = true;
  } // 账户的密码也要清除
  MyRef.value?.acceptParams();
};

// -----------------表单
const formRef = ref<FormInstance>();
// 提交
const submit = () => {
  formRef.value?.validate(async valid => {
    if (valid) {
      try {
        const params: any = {
          ...drawerProps.value.rowData,
          belong: drawerProps.value.pid ? drawerProps.value.pid : undefined
        };
        await drawerProps.value.api!(params);
        ElMessage.success("成功!");
        await drawerProps.value.getTable!();
        MyRef.value?.close();
      } catch (error) {}
    }
  });
};

// 监听二维码
watch(
  () => drawerProps.value.rowData.id,
  async () => {
    if (drawerProps.value.rowData.qrcode === "" && drawerProps.value.isEdit) {
      console.log("无二维码");
      const { data } = await genCode({ id: drawerProps.value.rowData.id });
      drawerProps.value.rowData.qrcode = data as any;
      await drawerProps.value.getTable!();
    }
  },
  {}
);

defineExpose({
  acceptParams
});
</script>

<style></style>
